package com.huazai.juc.cec.thread.july.twentyOne;

import com.huazai.juc.utils.SleepUtil;

import java.util.concurrent.*;

/**
 * 消费者和生产者的异步demo, 本demo中简单的使用了一下线程池
 */
public class AsynchronousDemo {
    public static void main(String[] args) {
        MessageQueue messageQueue = new MessageQueue(2);
        ExecutorService executorService = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r);
            }
        }, new ThreadPoolExecutor.CallerRunsPolicy());

        for (int i = 0; i < 3; i ++) {
            int id = i;
            new Thread(() -> {
                Message message = new Message(id, "值为" + id);
                messageQueue.put(message);
            }, "生产者" + (i + 1)).start();
        }

        executorService.execute(
            new Thread(() -> {
                while (true) {
                    SleepUtil.MySleep(1);
                    Message message = messageQueue.take();
                }
            }, "消费者")
        );

//        new Thread(() -> {
//            while (true) {
//                SleepUtil.MySleep(1);
//                Message message = messageQueue.take();
//            }
//        }, "消费者").start();
    }
}
